package com.hezuti.common.utils;



import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookieutil 工具类
 * 
 * @author xiaoyu.dou
 *
 */
public class CookieUtil {
	/**
	 * response中添加一个cookie
	 * @param res		HttpServletResponse对象
	 * @param cookie	Cookie对象
	 */
	public static void writeCookie(HttpServletResponse res,Cookie cookie){
		res.addCookie(cookie);
	}
	/**
	 * response中添加cookie集合
	 * @param res		HttpServletResponse对象
	 * @param cookies	List<Cookie>集合
	 */
	public static void writeCookies(HttpServletResponse res,List<Cookie> cookies){
		for(Cookie c:cookies){
			writeCookie(res,c);
		}
	}
	/**
	 * 创建一个Cookie
	 * @param key		
	 * @param value		
	 * @param pattern	作用域
	 * @param expiry	有效时间
	 * @return Cookie对象
	 */
	public static Cookie buildCookie(String key,String value,String pattern,int expiry,String path){
		Cookie c =new Cookie(key,value);
		c.setDomain(pattern);
		c.setMaxAge(expiry);
		c.setPath(path);
		return c;
	}
	/**
	 * 创建一个Cookie 集合
	 * @param keyValues key_valueMap对象
	 * @param pattern 作用域
	 * @param expiry	有效时间
	 * @return 返回 Cookie集合
	 */
	public static List<Cookie> buildCookies(Map<String,String> keyValues,String pattern,int expiry,String path){
		List cookies=new ArrayList<Cookie>();
		Set<String> keys = keyValues.keySet();
		for(String key:keys){
			cookies.add(buildCookie(key,keyValues.get(key),pattern,expiry,path));
		}
		return cookies;
		
	}
	/**
	 * 从requset的cookies中取出key 的value
	 * @param request	HttpServletRequest对象
	 * @param key
	 * @return 存在：String <BR/>不存在：NULL
	 */
	public static String getValueFromCookies(HttpServletRequest request,String key) {
		
		Cookie[] cookies = request.getCookies();
		for(Cookie c:cookies){
			if(key.equals(c.getName())){
				return c.getValue();
			}
		}
		return null;
	}
	
}
